package com.api.oa.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import org.apache.poi.xssf.streaming.SXSSFSheet;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class ToolUtils {


    public static void downLoadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
        BigExcelWriter writer = (BigExcelWriter) ExcelUtil.getBigWriter();
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list, true);
        // writer.close();
        SXSSFSheet sheet = (SXSSFSheet) writer.getSheet();
        //上面需要强转SXSSFSheet  不然没有trackAllColumnsForAutoSizing方法
        sheet.trackAllColumnsForAutoSizing();
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", String.format("attachment;filename=%s.xlsx", DateUtil.date().toString()));
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
        // 终止后删除临时文件
        //file.deleteOnExit();

    }

}
